package com.example.myapplication;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private Button start;
    private Button stop;
    private boolean isRunning = false;
    private boolean bound = false;
    private ServiceConnection connection;
    private PositionService positionService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder service) {
                PositionService.PositionBinder binder = (PositionService.PositionBinder) service;
                positionService = binder.getPosition();
                bound = true;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                bound = false;
            }
        };
        start = findViewById(R.id.start);
        stop = findViewById(R.id.stop);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isRunning = true;
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isRunning = false;
            }
        });

        getPosition();
    }

    private double latitude = 0.0;
    private double longitude = 0.0;
    private String time = "";
    public void getPosition() {
        final TextView latitudeView = findViewById(R.id.latitude);
        final TextView longitudeView = findViewById(R.id.longitude);
        final TextView timeView = findViewById(R.id.time);
        Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (isRunning && bound && positionService != null) {
                    latitude = positionService.getLatitude();
                    longitude = positionService.getLongitude();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd---HH:mm:ss");
                    Date date = new Date(System.currentTimeMillis());
                    time = format.format(date);
                }
                latitudeView.setText("纬度：" + String.valueOf(latitude));
                longitudeView.setText("经度：" + String.valueOf(longitude));
                timeView.setText("时间：" + time);
                handler.postDelayed(this, 1000);
            }
        });
    }

    private final int PERMISSION_REQUEST_CODE = 698;
    @Override
    protected void onStart() {
        super.onStart();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
        } else {
            Intent intent = new Intent(this, PositionService.class);
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (bound) {
            unbindService(connection);
            bound = false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(this, PositionService.class);
                    bindService(intent, connection, Context.BIND_AUTO_CREATE);
                } else {
                    Toast.makeText(this, "Location permission required", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putDouble("latitude", latitude);
        outState.putDouble("longitude", longitude);
        outState.putString("time", time);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        latitude = savedInstanceState.getDouble("latitude");
        longitude = savedInstanceState.getDouble("longitude");
        time = savedInstanceState.getString("time");
    }
//private ServiceConnection connection;
//    private OdometerService odometerService;
//    private boolean bound =false;
//    Button stop;
//    double dis = 0.0;
//    double lati = 0.0;
//    double longi = 0.0;
//    private boolean isstop = false;
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//        if(savedInstanceState!=null)
//        {
//            dis = savedInstanceState.getDouble("meter");
//            lati = savedInstanceState.getDouble("latitude");
//            longi = savedInstanceState.getDouble("longitude");
//            isstop = savedInstanceState.getBoolean("isstop");
//        }
//        stop = findViewById(R.id.Stop);
//        stop.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Toast.makeText(MainActivity.this,"Stop",Toast.LENGTH_LONG).show();
//                isstop=true;
//            }
//        });
//        /*
//         * 在activity内新建service，在onceates时使用匿名内部类来初始化，
//         *初始化connection，使用匿名内部类，new关键字后面，直接跟类的定义
//         *类实现两个方法 onServiceconnect, onservicedisconnected
//         * */
//        connection = new ServiceConnection() {
//            @Override
//            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//                OdometerService.OdometerBinder binder =(OdometerService.OdometerBinder) iBinder;
//                odometerService = binder.getOdometer();
//                bound = true;
//            }
//
//            @Override
//            public void onServiceDisconnected(ComponentName componentName) {
//                bound = false;
//            }
//        };
//
//        display();
//    }
//    //绑定服务
//    private final int PERMISSION_REQUEST_CODE = 698;
//    @Override
//    protected void onStart() {
//
//        super.onStart();
//        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
//        {
//            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_REQUEST_CODE);
//        }
//        else
//        {
//            Intent intent = new Intent(this,OdometerService.class);
//            bindService(intent,connection, Context.BIND_AUTO_CREATE);
//        }
//    }
//
//    //解绑服务
//    @Override
//    protected void onStop() {
//
//        super.onStop();
//        if(bound)
//        {
//            unbindService(connection);
//            bound=false;
//        }
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case PERMISSION_REQUEST_CODE: {
//                if (grantResults.length > 0 &&
//                        grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    Intent intent = new Intent(this, OdometerService.class);
//                    bindService(intent, connection, Context.BIND_AUTO_CREATE);
//                } else {
//                    Toast.makeText(this,"Location permission required",Toast.LENGTH_LONG).show();
//                }
//            }
//        }
//    }
//
//
//    //调用服务的方法
//    private void display()
//    {
//        final TextView meter = findViewById(R.id.meter);//距离
//        final TextView latitude = findViewById(R.id.Latitude);//纬度
//        final TextView longitude = findViewById(R.id.longitude);//经度
//        final TextView time = findViewById(R.id.Time);
//        final Handler handler = new Handler();
//        handler.post(new Runnable() {
//            @Override
//            public void run() {
//                    if(bound && odometerService!=null && !isstop)
//                    {
//                        dis = odometerService.getDistance();
//                        lati = odometerService.getLatitude();
//                        longi = odometerService.getLongitude();
//                    }
//                    String dstr = String.format(Locale.getDefault(),"%1$,.3f KM",dis);
//                    meter.setText(dstr);
//                    String a = String.format("%.10f",lati);
//                    String b = String.format("%.10f",longi);
//                    latitude.setText("纬度："+a);
//                    longitude.setText("经度："+b);
//                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    Date d = new Date(System.currentTimeMillis());
//                    time.setText(dateFormat.format(d));
//                    handler.postDelayed(this,1000);
//                }
//        });
//    }
//    // 保持屏幕的数据
//    @Override
//    protected void onSaveInstanceState(Bundle savedInstanceState) {
//        super.onSaveInstanceState(savedInstanceState);
//        savedInstanceState.putDouble("meter",dis);
//        savedInstanceState.putDouble("latitude",lati);
//        savedInstanceState.putDouble("longitude",longi);
//        savedInstanceState.putBoolean("isstop",isstop);
//    }
//
//    @Override
//    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
//        super.onRestoreInstanceState(savedInstanceState);
//        dis = savedInstanceState.getDouble("meter");
//        lati = savedInstanceState.getDouble("latitude");
//        longi = savedInstanceState.getDouble("longitude");
//        isstop = savedInstanceState.getBoolean("isstop");
//    }
}